package com.example.qihuibao.widget.dialog

import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.base.BaseDialogFragment
import com.example.qihuibao.bean.Department
import com.example.qihuibao.bean.ReqDeleteDepartmentInfoBean
import com.example.qihuibao.bean.RspQueryDepartmentInfoBean
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.extension.toast
import com.example.qihuibao.widget.view.CommonRecyclerView

/**
 *@author: cww
 *@desc:企业信息操作
 *@date: 5/16/23 10:58 AM
 */
class DepartmentInfoQueryDialog() : BaseDialogFragment(R.layout.dialog_department_info_query) {
    private var deleteIndex = -1
    private var list = mutableListOf<Department>()

    override fun initView() {
        mView?.findViewById<View>(R.id.iv_close)?.setOnClickListener { dismiss() }
        (activity as MainActivity).getMainViewModel().queryDepartmentInfo().observe(this) {
            if (it.RetCode == "0") {
                if (!it.DepList.isNullOrEmpty()) {
                    list.addAll(it.DepList!!)
                }
                mView?.findViewById<CommonRecyclerView>(R.id.rv_department)?.init(
                    R.layout.item_text_with_delete,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    list,
                    {parent, pos ->
                        parent.findViewById<TextView>(R.id.tv_content).text = "${getString(R.string.department_name1)}：${list!![pos].DepName1}\n${getString(R.string.department_name2)}：${list!![pos].DepName2}"
                    },
                    onItemLongClick = {pos, view ->
                        view.findViewById<TextView>(R.id.tv_delete).visibility = if (view.findViewById<TextView>(R.id.tv_delete).visibility == View.VISIBLE) View.GONE else View.VISIBLE
                        view.findViewById<TextView>(R.id.tv_delete).setOnClickListener { delete() }
                        deleteIndex = pos
                    }
                )
            }
        }
    }

    private fun delete() {
        (activity as MainActivity).getMainViewModel().deleteDepartmentInfo(ReqDeleteDepartmentInfoBean(list[deleteIndex].DepID1)).observe(this) {
            if (it.RetCode == "0") {
                if (list.size > deleteIndex) {
                    list.removeAt(deleteIndex)
                }
                mView?.findViewById<CommonRecyclerView>(R.id.rv_department)?.adapter?.notifyDataSetChanged()
                activity?.toast("删除成功")
            }else {
                activity?.toast("删除失败")
            }
        }
    }

}